package com.example.lamdba;

//004 四大内置函数式接口

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/*
 * Java8内置的四大核心函数式接口
 * 1、Consumer<T>:消费型接口
 *  void accept(T t);
 *
 * 2、Supplier<T>:供给型接口
 *  T get();
 *
 * 3、Function<T,R>:函数型接口，映射
 *  R apply(T t);
 *
 * 4、Predicate<T>:断言型接口
 *  boolean test(T t);
 */
public class TestLambda3 {

    //Consumer<T>:消费型接口
    @Test
    public void test1() {
        happy(10000, (m) -> System.out.println("消费" + m));
    }

    public void happy(double money, Consumer<Double> con) {
        con.accept(money);
    }

    //Supplier<T>:供给型接口
    @Test
    public void test2() {
        List<Integer> numberList = getNumberList(10, () -> (int) (Math.random() * 100));
        numberList.forEach(System.out::println);
    }

    //需求：产生一些整数，并放入集合
    public List<Integer> getNumberList(int num, Supplier<Integer> sup) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            list.add(sup.get());
        }
        return list;
    }

    //Function<T,R>:函数型接口，映射
    @Test
    public void test3() {
        String s1 = strHandler("     Hi", (s) -> s.trim());
        System.out.println(s1);

        String s2 = strHandler("aaaa", (s) -> s.toUpperCase());
        System.out.println(s2);
    }

    //需求：用于处理字符串
    public String strHandler(String str, Function<String, String> fun) {
        return fun.apply(str);
    }

    //Predicate<T>:断言型接口
    @Test
    public void test4() {
        List<String> stringList = Arrays.asList("aa", "bbb", "cccc", "eeeeee");
        List<String> filterStr = filterStr(stringList, (s) -> s.length() > 3);
        filterStr.forEach(System.out::println);
    }

    //需求：将满足条件的字符串，放入集合中
    public List<String> filterStr(List<String> list, Predicate<String> pre) {
        List<String> strList = new ArrayList<>();
        for (String str : list) {
            if (pre.test(str)) {
                strList.add(str);
            }
        }
        return strList;
    }

}
